<template>
  <div class="table-box">
    <Table ref="tableRef" row-key="id" :columns="columns" :request-api="microEntityApi.list">
      <template #header>
        <ElButton type="primary" icon="CirclePlus" @click="handleAdd">新增实体</ElButton>
      </template>
      <!-- 菜单操作 -->
      <template #action="{ row, id }">
        <TableAction :actions="getActions(row, id)" :show-num="0"></TableAction>
      </template>
    </Table>
    <Dialog ref="dialogRef" @submit="handleSubmit" :title="title" fullscreen @open="openWatch">
      <div class="card">
        <Form ref="basicFormRef" :schemas="basicSchemas" label-width="80px">
          <template #datasourceId="{ formModel, schema }">
            <ApiSelect
              v-model="formModel[schema.field]"
              :request-api="datasourceApi.listAll"
              label-name="datasourceName"
              value-name="id"
              :disabled="!!formModel.id"
            ></ApiSelect>
          </template>
          <template #tableName="{ formModel, schema }">
            <Select v-model="formModel[schema.field]" :options="tableList" :disabled="!!formModel.id">
              <template #default="{ item }">
                <div style="display: flex; justify-content: space-between">
                  <div>{{ item.value }}</div>
                  <div>{{ item.remark }}</div>
                </div>
              </template>
            </Select>
          </template>
        </Form>
      </div>
      <br />
      <div style="height: calc(100vh - 330px)">
        <Table row-key="id" :data="fieldList" :columns="tableFieldColumns" :show-search="false" :pagination="false">
          <template #dictType="{ row }">
            <Select v-model="row['dictType']" :options="dictList" label-name="dictName" value-name="dictType"> </Select>
          </template>
          <template #header>
            <ElButton v-if="showSync" type="primary" icon="refresh" @click="handleRefresh">同步</ElButton>
          </template>
        </Table>
      </div>
    </Dialog>
  </div>
</template>

<script setup lang="tsx" name="MicroEntity">
import { ref, watch } from "vue";
import { ElButton } from "element-plus";
import { Table, TableAction, useTable } from "@/components/Table";
import { Dialog, useDialog } from "@/components/Dialog";
import { Form, useForm, ApiSelect, Select } from "@/components/Form";
import { ActionItem } from "@/components/Table/type";
import datasourceApi from "@/views/system/datasource/api";
import microEntityApi from "./api";
import { columns, basicSchemas, tableFieldColumns } from "./data";
import dictTypeApi from "@/views/system/dict-type/api";
const tableRef = ref();
const dialogRef = ref();
const basicFormRef = ref();
const { getTableList } = useTable(tableRef);
const { open, close, openLoading } = useDialog(dialogRef);
const basicForm = useForm(basicFormRef);
const tableList = ref([]);
const fieldList = ref([]);
const title = ref("");
const tableModel = ref([]);
const showSync = ref(false);
const dictList = ref([]);
const openWatch = async () => {
  dictList.value = await dictTypeApi.listAll();
  const formModel = await basicForm.getFields();
  watch(
    () => formModel.datasourceId,
    async datasourceId => {
      if (datasourceId) {
        const res = (await datasourceApi.listTable({ datasourceId })) || [];
        tableList.value = res.map(r => {
          const result = { label: "", remark: "", value: "" };
          result.label = r.table;
          result.remark = r.remark;
          result.value = r.table;
          return result;
        });
      } else {
        tableList.value = [];
      }
    }
  );
  watch(
    () => formModel.tableName,
    async table => {
      if (!showSync.value) {
        if (table) {
          for (const tab of tableList.value) {
            if (tab.value === table) {
              if (!formModel.entityCode) {
                formModel.entityCode = tab.value;
              }
              if (!formModel.entityName) {
                formModel.entityName = tab.remark;
              }
              break;
            }
          }
          fieldList.value = await getFieldList();
        } else {
          fieldList.value = [];
        }
      }
    }
  );
};
const getFieldList = async () => {
  const formModel = await basicForm.getFields();
  const res = (await datasourceApi.listField({ datasourceId: formModel.datasourceId, table: formModel.tableName })) || [];
  const fieldList = res.map(row => {
    let fieldType;
    switch (row.dataType) {
      case -7:
      case -6:
      case 5:
      case 4:
      case -5:
      case 6:
      case 7:
      case 8:
      case 2:
      case 3:
        fieldType = "number";
        break;
      case -1:
      case -2:
      case -4:
      case 2004:
      case 2005:
        fieldType = "text";
      case 91:
      case 92:
      case 93:
        fieldType = "date";
        break;
      default:
        fieldType = "string";
        break;
    }
    return {
      fieldName: row.remark,
      fieldCode: row.column,
      pk: !!row.pk ? 1 : 0,
      required: !row.nullable ? 1 : 0,
      fieldType
    };
  });
  return fieldList;
};
const handleRefresh = async () => {
  const fieldMap = {};
  for (const field of fieldList.value) {
    fieldMap[field.fieldCode] = field;
  }
  const newFieldList = await getFieldList();
  const curFieldList = [];
  for (const field of newFieldList) {
    const oldField = fieldMap[field.fieldCode];
    if (oldField) {
      oldField.pk = field.pk;
      oldField.required = field.required;
      oldField.fieldType = field.fieldType;
      curFieldList.push(oldField);
    } else {
      curFieldList.push(field);
    }
  }
  fieldList.value = curFieldList;
};
const handleAdd = async () => {
  title.value = "新增实体";
  showSync.value = false;
  await open(0);
  await basicForm.resetFields();
  tableModel.value = [];
};
const handleSubmit = async flag => {
  const fields = await basicForm.validateFields();
  fields.fieldList = fieldList.value;
  await openLoading(async () => {
    if (flag) {
      await microEntityApi.edit(fields);
    } else {
      await microEntityApi.add(fields);
    }
    close();
    await getTableList();
  });
};
const getActions = (row, id): Partial<ActionItem>[] => {
  return [
    {
      type: "primary",
      icon: "edit",
      onClick: async () => {
        title.value = "编辑实体";
        showSync.value = true;
        await open(1);
        await basicForm.updateFields(row);
        fieldList.value = await microEntityApi.listField({ id });
      }
    },
    {
      type: "danger",
      popConfirm: {
        onConfirm: async () => {
          await microEntityApi.remove(id);
          await getTableList();
        }
      },
      icon: "delete"
    }
  ];
};
</script>
